package com.cm.admin.config;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.cm.admin.interceptor.LoginInterceptor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @类 名:WebAppConfigurer </br>
 * @描 述:<br>
 * @日 期:2020/9/21 17:38 </br>
 * @作 者:小兰同学</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@Slf4j
public class WebAppConfigurer extends WebMvcConfigurationSupport {
    @Autowired
    private LoginInterceptor loginInterceptor;
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                //.allowedOrigins("http://192.168.89.89")
                //rest集中请求方式
                .allowedMethods("*")
                .allowCredentials(false)
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
//                .addPathPatterns("/**");
                .addPathPatterns("/**")
                .excludePathPatterns("/index/login");
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        /**
         * 1. 排除掉原来的MappingJackson2HttpMessageConverter
         */
        List<MappingJackson2HttpMessageConverter> originalConverters = new ArrayList<>();
        // 原来的转换器
        for (HttpMessageConverter<?> converter : converters) {
            // 获取原始转换器集合
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                originalConverters.add((MappingJackson2HttpMessageConverter) converter);
            }
        }
        // 从原始转换器中移除原来转换器
        if (CollectionUtils.isNotEmpty(originalConverters)) {
            converters.removeAll(originalConverters);
        }
        /**
         * 2. 将long类型的数据转为String类型
         */
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        simpleModule.addSerializer(long.class, ToStringSerializer.instance);
        /**
         * 3. LocalDateTime 转换
         */
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 日期序列化格式(LocalDateTime转String)
        javaTimeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        // 日期反序列化格式(String转LocalDateTime)，这里需要注意，格式必须为yyyy-MM-dd HH:mm:ss
        javaTimeModule.addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        /**
         * 4. 构建ObjectMapper
         */
        ObjectMapper objectMapper =  Jackson2ObjectMapperBuilder
                .json()
                .modules(javaTimeModule,simpleModule)   // 添加模块
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
                .build();
        // Date的 序列化与反序列化
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 必须添加，如果不添加格式化日期将不正确
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        /**
         * 5. 创建MappingJackson2HttpMessageConverter对象
         */
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        // 将objectMapper添加到消息转换器
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        // 添加转换器到集合
        converters.add(jackson2HttpMessageConverter);
    }
}
